package mq.common;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.SneakyThrows;

/**
 * @author zhenglian
 * 通用channel 工厂类
 */
public class ChannelFactory {

    private static Connection connection;

    private static Channel channel;

    private final static int PORT = 5672;

    public static Channel newInstance(String host) {
        if (channel != null) {
            return channel;
        }
        channel = createChannel(host, PORT);
        return channel;
    }

    @SneakyThrows
    private static Channel createChannel(String host, int port) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connection = connectionFactory.newConnection();
        return connection.createChannel();
    }

    @SneakyThrows
    public static void closeChannel() {
        if (channel != null) {
            channel.close();
        }

        if (connection != null) {
            connection.close();
        }

    }


}
